﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace CommonUtil
{
    public class RegexHelper
    {
        /// <summary>
        /// 判断是否IP地址
        /// </summary>
        /// <param name="IPString"></param>
        /// <returns></returns>
        public static bool IsIPAddress(string IPString)
        {
            Regex pattern = new Regex(@"((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))");
            if (pattern.IsMatch(IPString)) return true;
            else return false;
        }
        /// <summary>
        /// 判断是否端口
        /// </summary>
        /// <param name="PortString"></param>
        /// <returns></returns>
        public static bool IsPort(string PortString)
        {
            if (IsNumber(PortString))
            {
                int port = int.Parse(PortString);
                if (port >= 0 && port <= 25535)
                {
                    return true;
                }
                else return false;
            }
            else return false;
        }

        /// <summary>
        /// 判断是否数字
        /// </summary>
        /// <param name="NumString"></param>
        /// <returns></returns>
        public static bool IsNumber(string NumString)
        {
            string pattern = @"^[0-9]*$";
            Match m = Regex.Match(NumString, pattern);
            if (m.Success) return true;
            else return false;
        }

        public static bool IsSpecialChar(string srcString, string spString)
        {
            if (spString == null)
            {
                spString = "`~!@#$%^&*()';:|,./?";
            }
            return Regex.IsMatch(srcString, spString);
        }
        public static string[] SplitConnectionString(string connString)
        {
            //Data Source=127.0.0.1;Initial Catalog=ADBTest;user id=sa;pwd=sa
            string[] arrSplit = null;
            if (connString.StartsWith(@"Data Source="))
            {
                string[] arrStr = connString.Split(';');
                string ip = arrStr[0].Replace(@"Data Source=", "");//.Split('\\')[0];
                string db = arrStr[1].Replace(@"Initial Catalog=", "");
                string uid = arrStr[2].Replace(@"user id=", "");
                string pwd = arrStr[3].Replace(@"pwd=", "");

                arrSplit = new string[] { ip, db, uid, pwd };
            }
            return arrSplit;
        }

        #region 查找以xx开头yy结尾的字符串
        /// <summary>
        /// 查找中间字符串返回类型
        /// </summary>
        public enum ReturnType
        {
            /// <summary>
            /// 返回第一个
            /// </summary>
            FirstString = 0,
            /// <summary>
            /// 返回所有
            /// </summary>
            StringArrary = 1
        }
        /// <summary>
        /// 查找以xx开头yy结尾的字符串
        /// </summary>
        /// <param name="srcString">要查找的字符串</param>
        /// <param name="beginString">以xx字符开头(忽略大小写)</param>
        /// <param name="endString">以yy字符结尾(忽略大小写)</param>
        /// <param name="returnType">FirstString返回第一个匹配的字符串 StringArrary返回所有匹配的字符串</param>
        /// <returns></returns>
        public static string[] RegexFindMiddleString(string srcString, string beginString, string endString, ReturnType returnType)
        {
            //20130313 clt add 
            string[] specChar = new string[] { @"\", "?", "*", "^", "$", "+", "(", ")", "|", "[", "]", "{", "}" };
            for (int i = 0; i < specChar.Length; i++)
            {
                beginString = beginString.Replace(specChar[i], @"\" + specChar[i]);
                endString = endString.Replace(specChar[i], @"\" + specChar[i]);
            }

            string[] result = null;
            string express = @"(?s)(?<=" + beginString + @").*?" + @"(?=" + endString + @")";
            Regex reg = new Regex(express, RegexOptions.IgnoreCase);
            MatchCollection mc = reg.Matches(srcString);
            result = new string[mc.Count];
            if (returnType == ReturnType.FirstString)
            {
                result[0] = string.Empty;
                foreach (Match m in reg.Matches(srcString))
                {
                    result[0] = result[0] + m.Value + "|";
                }
                result[0].TrimEnd(new char[] { '|' });
            }
            if (returnType == ReturnType.StringArrary)
            {
                for (int i = 0, j = mc.Count; i < j; i++)
                {
                    result[i] = mc[i].Value;
                }
            }
            return result;
        }
        //20130313 clt add 
        /// <summary>
        /// 查找以xx开头yy结尾的字符串
        /// </summary>
        /// <param name="srcString">要查找的字符串</param>
        /// <param name="beginString">以xx字符开头</param>
        /// <param name="endString">以yy字符结尾</param>
        /// <param name="returnType">FirstString返回第一个匹配的字符串 StringArrary返回所有匹配的字符串</param>
        /// <param name="caseType">是否忽略大小写</param>
        /// <returns></returns>
        public static string[] RegexFindMiddleString(string srcString, string beginString, string endString, ReturnType returnType, RegexOptions caseType)
        {            
            string[] specChar = new string[] { @"\", "?", "*", "^", "$", "+", "(", ")", "|", "[", "]", "{", "}" };
            for (int i = 0; i < specChar.Length; i++)
            {
                beginString = beginString.Replace(specChar[i], @"\" + specChar[i]);
                endString = endString.Replace(specChar[i], @"\" + specChar[i]);
            }

            string[] result = null;
            string express = @"(?s)(?<=" + beginString + @").*?" + @"(?=" + endString + @")";
            Regex reg = new Regex(express, caseType);
            MatchCollection mc = reg.Matches(srcString);
            result = new string[mc.Count];
            if (returnType == ReturnType.FirstString)
            {
                result[0] = string.Empty;
                foreach (Match m in reg.Matches(srcString))
                {
                    result[0] = result[0] + m.Value + "|";
                }
                result[0].TrimEnd(new char[] { '|' });
            }
            if (returnType == ReturnType.StringArrary)
            {
                for (int i = 0, j = mc.Count; i < j; i++)
                {
                    result[i] = mc[i].Value;
                }
            }
            return result;
        }
        #endregion

        /// <summary>
        /// 返回用户可见菜单功能项
        /// </summary>
        /// <param name="strFunc">角色包含功能项: 1,2,3,4,5,6,7,8,9,10,11,12</param>
        /// <param name="strHidden">不可见功能项: 1,5,6,7,8</param>
        /// <param name="splitChar">分隔符：，</param>
        /// <returns>2,3,4,9,10,11,12</returns>
        public static string DifferSet(string strFunc, string strHidden, char splitChar)
        {
            if (string.IsNullOrEmpty(strFunc)) return "";
            if (string.IsNullOrEmpty(strHidden)) return strFunc;
            string differSetStr = "";

            string[] funStrArr = strFunc.Split(splitChar);
            System.Collections.ArrayList list = new System.Collections.ArrayList();
            foreach (string str in funStrArr)
            {
                list.Add(str);
            }

            string[] hiddenStrArr = strHidden.Split(splitChar);
            for (int i = 0; i < hiddenStrArr.Length; i++)
            {
                for (int j = 0; j < list.Count; j++)
                {
                    if (hiddenStrArr[i] == list[j].ToString())
                    {
                        list.Remove(hiddenStrArr[i]);
                    }
                }
            }

            foreach (string s in list)
            {
                differSetStr += s + splitChar.ToString();
            }
            if (differSetStr.IndexOf(splitChar) != -1)
                differSetStr = differSetStr.TrimEnd(splitChar);

            return differSetStr;
        }

        /// <summary>
        /// 求当前值加1后的值
        /// </summary>
        /// <param name="temp">传入的STring</param>
        /// <returns>如果成功反馈true，否则False</returns>
        public static bool getnext(ref string temp)
        {
            bool isget = false;
            char[] LETTER = new char[26] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
            char[] letter = new char[26] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
            char[] Num = new char[10] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
            char[] arraychar = temp.ToCharArray();
            if (arraychar != null && arraychar.Length > 0)
            {
                for (int i = arraychar.Length - 1; i >= 0; i--)
                {
                    int letterIndex = NextCharIndex(arraychar[i], letter);
                    int LETTERIndex = NextCharIndex(arraychar[i], LETTER);
                    int NumIndex = NextCharIndex(arraychar[i], Num);
                    if (letterIndex != -1)
                    {
                        if (letterIndex == -2)
                        {
                            arraychar[i] = letter[0];
                        }
                        else
                        {
                            arraychar[i] = letter[letterIndex];
                            break;
                        }
                    }
                    else if (LETTERIndex != -1)
                    {
                        if (LETTERIndex == -2)
                        {
                            arraychar[i] = LETTER[0];
                        }
                        else
                        {
                            arraychar[i] = LETTER[LETTERIndex];
                            break;
                        }
                    }
                    else if (NumIndex != -1)
                    {
                        if (NumIndex == -2)
                        {
                            arraychar[i] = Num[0];
                        }
                        else
                        {
                            arraychar[i] = Num[NumIndex];
                            break;
                        }
                    }
                    if (i == 0 && (LETTERIndex == -2 || letterIndex == -2 || NumIndex == -2))
                    {
                        return isget;
                    }
                }
                temp = string.Empty;
                isget = true;
                for (int i = 0; i < arraychar.Length; i++)
                {
                    temp += arraychar[i].ToString();
                }
                return isget;
            }
            else
                return isget;
        }

        /// <summary>
        /// char类型和Char数组进行比较，如果在数据中存在，那么对其索引值加1后返回，
        /// 如果为-1则不存在，如果为-2则代表是当前数据的最后一个数
        /// </summary>
        /// <param name="chartmp">录入Char</param>
        /// <param name="_charArray">CharArray</param>
        /// <returns>下一个索引值</returns>
        private static int NextCharIndex(char chartmp, char[] _charArray)
        {
            int newIndex = -1;
            for (int i = 0; i < _charArray.Length; i++)
            {
                if (_charArray[i].Equals(chartmp))
                {
                    if (i + 1 == _charArray.Length)
                    {
                        newIndex = -2;
                    }
                    else
                    {
                        newIndex = i + 1;
                    }
                    break;
                }
            }
            return newIndex;
        }

        #region 忽略大小写的字符串替换
        /// <summary>
        /// 忽略大小写的字符串替换
        /// </summary>
        /// <param name="mystring">字符串源</param>
        /// <param name="oldValue">需要替换的字符串</param>
        /// <param name="newValue">替换后的值</param>
        /// <returns></returns>
        public static string ReplaceIgnoreCase(string mystring, string oldValue, string newValue)
        {
            try
            {
                string lowerword = oldValue.ToLower();
                string lowerstring = mystring.ToLower();
                while (lowerstring.IndexOf(lowerword) > -1)
                {
                    mystring = mystring.Substring(0, lowerstring.IndexOf(lowerword)) + newValue + mystring.Substring(lowerstring.IndexOf(lowerword) + lowerword.Length);
                    lowerstring = lowerstring.Substring(0, lowerstring.IndexOf(lowerword)) + newValue + lowerstring.Substring(lowerstring.IndexOf(lowerword) + lowerword.Length);
                }
            }
            catch (System.Exception ex)
            {
                Logger.DefaultLog(ex.ToString(), LogType.Error);
            }
            return mystring;
        }
        #endregion

    }
}
